package com.e3.web.core.client;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;

public class AjaxRequest {

	private RequestBuilder builder;

	private AjaxCallback ajaxCallback;

	public AjaxRequest(String url, boolean isPOST, AjaxCallback callback) {
		this.ajaxCallback = callback;
		if (isPOST)
			builder = new RequestBuilder(RequestBuilder.POST, url);
		else
			builder = new RequestBuilder(RequestBuilder.GET, url);

		builder.setHeader("Content-type", "application/x-www-form-urlencoded");
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				ajaxCallback.onFail("loading data err");
			}

			public void onResponseReceived(Request request, Response response) {
				ajaxCallback.onSuccess(response.getText());
			}
		});
	}

	public void send(String ReuestData) {
		builder.setRequestData(ReuestData);
		try {
			builder.send();
		} catch (RequestException e) {
			ajaxCallback.onFail(e.getLocalizedMessage());
		}
	}

}
